<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文档标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入文档标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>

      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文档标题" align="center" prop="title" :show-overflow-tooltip="true"/>
      <el-table-column label="文档简介" align="center" prop="summary" :show-overflow-tooltip="true"/>
      <el-table-column label="是否可见" align="center" prop="isShow">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yes_or_no" :value="scope.row.isShow"/>
        </template>
      </el-table-column>
      <el-table-column label="阅读数量" align="center" prop="readCount"/>
      <el-table-column label="排序号" align="center" prop="sortNum"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180"/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:post:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文档标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文档标题"/>
        </el-form-item>
        <el-form-item label="文档简介" prop="summary">
          <el-input type="textarea" v-model="form.summary" placeholder="请输入文档简介"/>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="标签" prop="tags">
              <el-tag
                v-for="(item, index) of form.tags"
                :key="index"
                style="margin: 0 1rem 0 0"
                :closable="true"
                @close="removeTag(item)"
              >
                {{ item }}
              </el-tag>
              <!-- 标签选项 -->
              <el-popover
                placement="bottom-start"
                width="460"
                trigger="click"
                v-if="form.tags && form.tags.length < 3"
              >
                <div class="popover-title">标签</div>
                <!-- 搜索框 -->
                <el-input
                  style="width: 100%"
                  v-model="tagName"
                  placeholder="请输入标签名,enter添加自定义标签"
                  @keydown.enter.native.stop.prevent="saveTag"
                  @keyup.enter.native.stop.prevent="saveTag"
                />
                <!-- 标签 -->
                <div class="popover-container">
                  <div>添加标签</div>
                  <el-tag
                    v-for="(item, index) of tagOptions"
                    :key="index"
                    style="margin-left: 3px; margin-top: 2px"
                    @click="addTag(item.name)"
                  >
                    {{ item.name }}
                  </el-tag>
                </div>
                <template #reference>
                  <el-button type="primary" plain> 添加标签</el-button>
                </template>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否可见" prop="isShow">
              <el-select v-model="form.isShow" placeholder="请选择可见状态" clearable>
                <el-option
                  v-for="dict in dict.type.yes_or_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序号" prop="sortNum">
              <el-input-number v-model="form.sortNum" controls-position="right" :min="0" :max="99999999" placeholder="越大越靠前"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-col :span="24">
          <el-form-item label="内容">
            <mavon-editor
              v-model="form.content"
              ref="md"
              @imgAdd="$imgAdd"
              @change="change"
              style="min-height: 600px"
            />

          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {delDocs, getDetail, listDocs, saveDoc} from "@/api/official/docs"
import {listTags} from "@/api/official/tags"
import axios from 'axios'
import { getToken } from '@/utils/auth'

export default {
  name: "Post",
  dicts: ['yes_or_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      postList: [],
      // 标签数据
      tagOptions: [],
      tagName: "",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          {required: true, message: "文档标题不能为空", trigger: "blur"}
        ],
        tags: [
          {required: true, message: "请选择标签", trigger: "blur"}
        ],
        summary: [
          {required: true, message: "文档简介不能为空", trigger: "blur"}
        ],
        isShow: [
          {required: true, message: "可见状态不能为空", trigger: "blur"}
        ]
      }
    }
  },
  created() {
    this.getList()
    this.listTags()
  },
  methods: {
    /** 查询文档列表 */
    getList() {
      this.loading = true
      listDocs(this.queryParams).then(response => {
        this.postList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询文档列表 */
    listTags() {
      listTags({pageNum: 1, pageSize: 99999}).then(response => {
        this.tagOptions = response.rows
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        title: undefined,
        tags: [],
        sortNum: 0,
        content: undefined,
        isShow: undefined
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加文档"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      this.title = "修改文档"
      console.log('handleUpdate', id)
      getDetail(id).then(response => {
        this.form = response.data
        this.open = true
      })

    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          saveDoc(this.form).then(response => {
            if (this.form.id != undefined) {
              this.$modal.msgSuccess("修改成功")
            } else {
              this.$modal.msgSuccess("新增成功")
            }

            this.open = false
            this.reset()
            this.getList()
          })

        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {

      this.$modal.confirm('是否确认删除"' + row.title + '"的文档？').then(function () {
        return delDocs(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    // 将图片上传到服务器，返回地址替换到md中
    $imgAdd(pos, $file) {
      const formdata = new FormData()
      formdata.append('file', $file)
      axios({
        url: process.env.VUE_APP_BASE_API + '/system/file/upload',
        method: 'post',
        data: formdata,
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': 'Bearer ' + getToken()
        }
      }).then(res => {
        // 期望结构：{ code, msg, data: { fullPath } }
        const fullPath = res && res.data && res.data.data && res.data.data.fullPath
        if (fullPath) {
          this.$refs.md.$img2Url(pos, fullPath)
        } else {
          this.$modal.msgError('上传成功但未返回文件地址')
        }
      }).catch(err => {
        console.error('img upload error', err)
        this.$modal.msgError('上传图片失败')
      })
    },
    change(value, render) {
      this.html = render
    },
    addTag(name) {
      if (!this.form.tags) this.$set(this.form, 'tags', [])
      if (!name) return
      if (this.form.tags.length >= 3) return
      if (!this.form.tags.includes(name)) {
        this.form.tags.push(name)
      }
      this.tagName = ''
    },
    removeTag(name) {
      if (!this.form.tags) return
      this.form.tags = this.form.tags.filter(t => t !== name)
    },
    saveTag() {
      console.log('saveTag', this.tagName)
      const name = (this.tagName || '').trim()
      if (!name) return
      this.addTag(name)
    }
  }
}
</script>
